package com.hlm.demo.interceptors;

import com.hlm.demo.entity.ModuleInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author Ric
 * 此拦截器阻止用户通过地址栏访问无权限的页面
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        String permission = (String) session.getAttribute("permission");

        if (permission.equals("God")) {
            return true;
        }

        if (permission.equals("Admin")) {
            String servletPath = request.getServletPath();

            // urlComparator: 截取后的对比用数据 (例: /role/role_list => /role)
            String urlComparator = servletPath.substring(0, servletPath.indexOf("/", 2));

            System.out.println("权限拦截器已拦截URL = " + servletPath);

            List<ModuleInfo> moduleInfoList = (List<ModuleInfo>) session.getAttribute("moduleInfo");


            for (ModuleInfo info : moduleInfoList) {
                if (info.getLinkAddress().startsWith(urlComparator) || urlComparator.startsWith("/info")) {
                    System.out.println("OK!");
                    return true;
                }

            }
            System.out.println("NG!");
            response.sendRedirect("/nopower.html");
            return false;


        }


        response.sendRedirect("/error.html");
        return false;

    }
}
